import 'package:flutter/material.dart';
import 'package:flutter_app/model/tweet.dart';
import 'package:flutter_app/style/color.dart';
import 'package:flutter_app/view/tweet/menu_build.dart';
import 'package:flutter_app/view/tweet/tweet_details.dart';
import 'package:flutter_app/view/photoViewGalleryScreen.dart';
import 'package:flutter_app/tools/utils.dart';

// ignore: must_be_immutable
class TweetGridItem extends StatefulWidget {
  final Tweet tweet;
  bool isDetailPage = false;
  TweetGridItem({@required this.tweet, Key key}) : super(key: key);

  @override
  TweetGridItemState createState() => TweetGridItemState(this);
}

// ignore: camel_case_types
class TweetGridItemState extends State<TweetGridItem> {
  TweetGridItem _tweetView;
  Widget likedMenu;
  TweetGridItemState(this._tweetView);

  @override
  void initState() {
    super.initState();
  }

  //收藏
  void _mark() {
    setState(() {
      if (_tweetView.tweet.isMarked) {
        _tweetView.tweet.markCount -= 1;
        _tweetView.tweet.isMarked = false;
      } else {
        _tweetView.tweet.markCount += 1;
        _tweetView.tweet.isMarked = true;
      }
    });
  }

  void refreshAddReplyCount() {
    _tweetView.tweet.repliesCount += 1;
    setState(() {});
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
//评论
    Function onTapped = (BuildContext context) {
      if (!_tweetView.isDetailPage) {
        Navigator.push(context, new MaterialPageRoute(builder: (_) {
          _tweetView.isDetailPage = true;
          return new TweetDetails(_tweetView);
        })).then((date) {
          setState(() {
            _tweetView = date;
          });
        });
      }
    };

    return Card(
      color: Colors.white,
      child: Center(
        child: InkWell(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              //用户名和发布时间
              Row(children: [
                Padding(
                    padding: EdgeInsets.fromLTRB(20, 10, 10, 10),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Padding(
                          padding: EdgeInsets.all(.0),
                          child: new Text(
                            _tweetView.tweet.userName,
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                            style: TextStyle(
                              fontSize: 18.0,
                              height: 1.2,
                            ),
                          ),
                        ),
                        Padding(
                            padding: EdgeInsets.all(.0),
                            child: new Text(
                              m_utils.timeDifferenceToNow(
                                  _tweetView.tweet.inTime, DateTime.now()),
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                              style: TextStyle(
                                color: m_color.grey,
                                fontSize: 12.0,
                                height: 1.2,
                              ),
                            ))
                      ],
                    ))
              ]),
              Divider(height: 0),
              //主要内容
              Container(
                margin: _tweetView.tweet.text.length == 0
                    ? EdgeInsets.all(0)
                    : EdgeInsets.fromLTRB(15.0, 5.0, 15.0, 5.0),
                alignment: Alignment.centerLeft,
                child: _tweetView.tweet.text.length == 0
                    ? null
                    : Text(_tweetView.tweet.text),
              ),
              //图片区域
              Container(
                margin: EdgeInsets.all(0),
                decoration: BoxDecoration(color: Color(0x66E0EEEE)),
                alignment: Alignment.center,
                child: buildImageView(context, _tweetView.tweet),
              ),

              Divider(height: 0),

              //菜单栏
              Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [menuWidget(_tweetView.tweet, iconSize: 24.0)],
              )
            ],
          ),
          onTap: _tweetView.isDetailPage
              ? null
              : () {
                  onTapped(context);
                },
        ),
      ),
    );
  }
}

Widget buildImageView(BuildContext context, Tweet tweet) {
  if (tweet.images.length > 1) {
    List<Widget> imageList = new List<Widget>();
    for (var i = 0; i < tweet.images.length; i++) {
      if (tweet.thumbnails[i].endsWith('.gif')) {
        imageList.add(InkWell(
            child: Stack(
              fit: StackFit.expand,
              children: [
                Container(
                  child: Image.network(tweet.thumbnails[i], fit: BoxFit.cover),
                ),
                Positioned(left: 5, bottom: 5, child: buildGifLogo())
              ],
            ),
            onTap: () {
              viewPhoto(context, tweet.images, tweet.thumbnails, i);
            }));
      } else {
        imageList.add(InkWell(
            child: Image.network(tweet.thumbnails[i], fit: BoxFit.cover),
            onTap: () {
              viewPhoto(context, tweet.images, tweet.thumbnails, i);
            }));
      }
    }

    return GridView(
      scrollDirection: Axis.vertical,
      shrinkWrap: true,
      physics: NeverScrollableScrollPhysics(),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 3,
        mainAxisSpacing: 2,
        crossAxisSpacing: 2,
      ),
      children: imageList,
    );
  } else if (tweet.images.length == 1) {
    if (tweet.thumbnails[0].endsWith('.gif')) {
      return InkWell(
          child: Stack(
            children: [
              Container(
                child: Image.network(tweet.thumbnails[0], fit: BoxFit.cover),
              ),
              Positioned(left: 12, bottom: 12, child: buildGifLogo())
            ],
          ),
          onTap: () {
            viewPhoto(context, tweet.images, tweet.thumbnails, 0);
          });
    } else {
      return InkWell(
          child: Image.network(tweet.thumbnails[0]),
          onTap: () {
            viewPhoto(context, tweet.images, tweet.thumbnails, 0);
          });
    }
  } else {
    return null;
  }
}

//点击图片查看高清图片。
viewPhoto(BuildContext context, List<String> images, List<String> thumbnails,
    int index) {
  //FadeRoute是自定义的切换过度动画（渐隐渐现） 如果不需要 可以使用默认的MaterialPageRoute
  Navigator.of(context).push(new MaterialPageRoute(builder: (context) {
    return PhotoViewGalleryScreen(
      images: images, //传入图片list
      thumbnails: thumbnails,
      heroTag: images[index],
      index: index, //传入当前点击的图片的index
    );
  }));
}

Widget buildGifLogo() {
  return Container(
    width: 38,
    height: 20,
    alignment: Alignment.center,
    decoration: BoxDecoration(
      color: Colors.black54,
      border: Border.all(color: Colors.white, width: 0.8),
      borderRadius: BorderRadius.all(Radius.circular(3)), // 也可控件一边圆角大小
    ),
    child: Text(
      "动图",
      style: TextStyle(color: Colors.white, fontSize: 12),
    ),
  );
}
